package com.cbz.learn.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试消费者
 */
public class KafkaConsumerTest {

    public static void main(String[] args) {

        // 配置map
        Map<String, Object> config = new HashMap<>();
        config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

        // 分组id  后面再说什么意思
        config.put(ConsumerConfig.GROUP_ID_CONFIG, "cbz");

        // 创建消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(config);
        // 订阅主题
        consumer.subscribe(Collections.singletonList("testTopic"));
        // 获取数据 消费者从kafka拉取数据 可能会拉取多条,第一个参数是超时时间

        // 持续接收消息
        while (true){
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record);
            }
        }

//        consumer.close();
    }
}
